/**
 * 通过注释解析出 className
 *
 * @param annotationContent
 * @returns {*[]}
 */
function parseClassNameByAnnotation(annotationContent) {
    let result = [];
    if (!annotationContent) {
        return result;
    }
    let annotationContentOfNew = annotationContent.replaceAll(/<!--|-->/g, '').trim();
    if (!annotationContentOfNew) {
        return result;
    }
    // <!-- class=xxx1,xxx2,xxx3 或 class= xxx1,xxx2,xxx3 -->
    if (!annotationContentOfNew.trim().startsWith("class=")) {
        return result;
    }
    console.log("加载自定义class配置[class=]", annotationContentOfNew);
    annotationContentOfNew = annotationContentOfNew.trim().replace("class=", "").trim();
    result = annotationContentOfNew.split(",");
    return result;
}

/**
 * 添加节点注解 className 到 a 标签
 */
function addNodeAnnotationClassNameToA(childNode){
    var childNodes = childNode.childNodes;
    for (let j = 0; j < childNodes.length; j++) {
        if (childNodes[j].nodeType !== Node.COMMENT_NODE) {
            continue;
        }
        let parseClassNameByAnnotation = this.parseClassNameByAnnotation(childNodes[j].nodeValue);
        parseClassNameByAnnotation.forEach(className => childNode.classList.add(className));
    }
}

/**
 * 获取节点注解的 className
 *
 * @param node
 * @returns {*[]}
 */
function getNodeAnnotationClassName (node){
    let classNameArray = [];
    let childNodes = node.childNodes;
    for (let i = 0; i < childNodes.length; i++) {
        let childNode = childNodes[i];
        // 移除UL元素
        if (childNode.nodeName === "UL") {
            continue;
        }
        // A元素，单独处理
        if (childNode.nodeName === "A") {
            this.addNodeAnnotationClassNameToA(childNode);
            continue;
        }
        // 检查是否存在注释className
        let nodeAnnotationClassName;
        if (childNode.nodeType === Node.COMMENT_NODE) {
            nodeAnnotationClassName = this.parseClassNameByAnnotation(childNode.nodeValue);
        }else {
            nodeAnnotationClassName = this.getNodeAnnotationClassName(childNode);
        }
        nodeAnnotationClassName.forEach(className => classNameArray.push(className));
    }
    return classNameArray;
}

/**
 * 载入插件
 *
 * @type {*[]}
 */
window.$docsify.plugins = [].concat(function(hook, vm) {

    // 钩子函数：每次路由切换时数据全部加载完成后调用，没有参数。
    hook.doneEach(function() {
        // 加载自定义 className 配置
        document.querySelectorAll('.sidebar-nav li').forEach(function(li) {
            let nodeAnnotationClassName = this.getNodeAnnotationClassName(li);
            nodeAnnotationClassName.forEach(className => li.classList.add(className));
        });
    });

}, window.$docsify.plugins);